Bird
Raised Fist0
RubyComparisonBeginner · 3 min read

Or vs || in Ruby: Key Differences and When to Use Each

In Ruby, or and || both perform logical OR operations but differ in precedence. || has higher precedence, making it suitable for boolean logic in expressions, while or has lower precedence and is often used for control flow to combine statements clearly.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of or and || in Ruby.

Featureor||
PrecedenceLow precedenceHigh precedence
Typical UseControl flow, combining statementsBoolean logic in expressions
Short-circuit behaviorYes, stops if left is trueYes, stops if left is true
AssociativityLeft-associativeLeft-associative
Common PitfallMay cause unexpected grouping in expressionsPreferred for complex boolean expressions
⚖️

Key Differences

The main difference between or and || in Ruby is their operator precedence. || has a higher precedence, which means it binds more tightly to the expressions around it. This makes || ideal for use in boolean expressions where you want to combine conditions precisely.

On the other hand, or has a lower precedence, which means it is evaluated after most other operators. This makes it useful for control flow, such as chaining commands or handling return values in a clear way without parentheses. For example, you can write do_something or raise_error to run the second command only if the first fails.

Both operators short-circuit, meaning they stop evaluating as soon as the result is known. However, because of the precedence difference, using or inside complex expressions can lead to unexpected results unless parentheses are used carefully.

⚖️

Code Comparison

Here is an example showing how || works in a boolean expression:

ruby
a = false
b = true
result = a || b
puts result
Output
true
↔️

Or Equivalent

Here is the equivalent example using or to combine statements with lower precedence:

ruby
a = false
b = true
result = a or b
puts result
puts result == a
Output
false true
🎯

When to Use Which

Choose || when you need to combine boolean expressions precisely, such as in conditionals or complex logic. It ensures the correct order of evaluation without surprises.

Choose or for control flow to chain commands or handle errors in a readable way, especially when you want to avoid parentheses and emphasize statement order.

Always be mindful of operator precedence to avoid bugs, and use parentheses if needed to clarify your intent.

✅

Key Takeaways

|| has higher precedence and is best for boolean logic.
or has lower precedence and is useful for control flow.
Both short-circuit but can behave differently in complex expressions.
Use parentheses to avoid confusion when mixing or with other operators.
Pick || for conditions, or for chaining commands.